package com.fumin.service;

import com.fumin.beans.PageQuery;
import com.fumin.beans.PageResult;
import com.fumin.common.RequestHolder;
import com.fumin.dao.SysUserMapper;
import com.fumin.exception.ParamException;
import com.fumin.model.SysUser;
import com.fumin.param.UserParam;
import com.fumin.util.BeanValidator;
import com.fumin.util.IpUtil;
import com.fumin.util.MD5Util;
import com.fumin.util.PasswordUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @Author xiayuxuanmin
 * @Date 2019/10/24
 * @Description
 */
@Service
public class SysUserService {
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysLogService sysLogService;

    /**
     * 新增
     * @param param
     */
    public void save(UserParam param){
        BeanValidator.check(param);//检测参数是否合法
        if (checkEmailExist(param.getMail(),param.getId())) {
            throw new ParamException("电话已经被占用!");
        }
        if (checkTelePhoneExist(param.getTelephone(),param.getId())) {
            throw new ParamException("电话已经被占用!");
        }
        String password = PasswordUtil.randomPassword();
        password = "123456";
        String encryptPassword = MD5Util.encrypt(password);
        SysUser user = SysUser.builder().username(param.getUsername()).telephone(param.getTelephone()).password(encryptPassword)
                       .mail(param.getMail()).deptId(param.getDeptId()).status(param.getStatus()).remark(param.getRemark())
                       .build();
        user.setOperator(RequestHolder.getCurrentUser().getUsername());
        user.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
        user.setOperateTime(new Date());
        // TODO:send Emial
        sysUserMapper.insertSelective(user);
        sysLogService.saveUserLog(null,user);
    }

    /**
     * 更新
     * @param param
     */
    public void update(UserParam param){
        BeanValidator.check(param);//检测参数是否合法
        if (checkEmailExist(param.getMail(),param.getId())) {
            throw new ParamException("电话已经被占用!");
        }
        if (checkTelePhoneExist(param.getTelephone(),param.getId())) {
            throw new ParamException("电话已经被占用!");
        }
        SysUser before = sysUserMapper.selectByPrimaryKey(param.getId());
        if (before == null) {
            throw new ParamException("待更新的用户不存在!");
        }
        SysUser after = SysUser.builder().id(param.getId()).password(before.getPassword()).username(param.getUsername()).telephone(param.getTelephone())
                .mail(param.getMail()).deptId(param.getDeptId()).status(param.getStatus()).remark(param.getRemark())
                .build();
        after.setOperator(RequestHolder.getCurrentUser().getUsername());
        after.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
        after.setOperateTime(new Date());
        sysUserMapper.updateByPrimaryKeySelective(after);
        sysLogService.saveUserLog(before,after);
    }

    public boolean checkEmailExist(String mail,Integer userId){
        return sysUserMapper.checkEmailExist(mail,userId) > 0;
    }

    public boolean checkTelePhoneExist(String telePhone,Integer userId){
        return sysUserMapper.checkTelePhoneExist(telePhone,userId) > 0;
    }

    /**
     * 通过关键字查找SysUser
     * @param keyword
     * @return
     */
    public SysUser findByKeyword(String keyword){
        return sysUserMapper.findByKeyword(keyword);
    }

    /**
     * 根据分页对象查找分页数据
     * @param deptId
     * @param page
     * @return
     */
    public PageResult<SysUser> getPageByDeptId(int deptId, PageQuery page) {
        BeanValidator.check(page);
        int count = sysUserMapper.countByDeptId(deptId);
        if (count > 0) {
            List<SysUser> list = sysUserMapper.getPageByDeptId(deptId, page);
            return PageResult.<SysUser>builder().total(count).data(list).build();
        }
        return PageResult.<SysUser>builder().build();
    }

    /**
     * 获取所有用户列表
     * @return
     */
    public List<SysUser> getAll() {
        return sysUserMapper.getAll();
    }
}
